#!/usr/bin/perl

package Guid;

sub bin_to_hex {
    my $s = shift;
    my $rval = "";
    
    my $v = ord(substr($s, 0, 1));
    return sprintf("%02x", $v);
}

sub substr_to_hex {
    my $s = shift;
    my $i = shift;

    return bin_to_hex(substr($s, $i, 1));
}

sub fourcc_to_string {
    my $fourcc = shift;
    my $rval = "";
    
    $rval .= "\"";
    foreach my $i ( 0..3 ) {
	my $c = substr($fourcc, $i, 1);
	my $v = ord($c);
	
	if ( $v == 0 ) { $c = " "; }
	elsif ( $v < 0x20 || $v >= 0x7f ) { $c = "?"; }
	$rval .= $c;
    }
    $rval .= "\" (";
    $rval .= string_to_hexstring($fourcc);
    $rval .= ")";
    
    return $rval;
}

sub new {
    my $pkg = shift;
    my $val = "";
    my $val1 = shift;
    my $hash = {};

    if ( $val1 =~ /^([0-9a-fA-F]{8})-([0-9a-fA-F]{4})-([0-9a-fA-F]{4})-([0-9a-fA-F]{4})-([0-9a-fA-F]{12})$/ ) {
#	print ("matched ms style format\n");
	
	$val1 =~ tr/A-F/a-f/;
	$val = $val1;
    } elsif ( length($val1) == 16 ) {
	my $i;

#	print ("matched 16 binaries\n");

	for ( $i = 3; $i>=0; $i-- ) { $val .= substr_to_hex($val1, $i); }
	$val .= "-";
	for ( $i = 5; $i>=4; $i-- ) { $val .= substr_to_hex($val1, $i); }
	$val .= "-";
	for ( $i = 7; $i>=6; $i-- ) { $val .= substr_to_hex($val1, $i); }
	$val .= "-";
	for $i ( 8..9 )	{ $val .= substr_to_hex($val1, $i); }
	$val .= "-";
	for $i ( 10..15 ) { $val .= substr_to_hex($val1, $i); }
    }    
    
    $hash = { val => $val };
    return bless $hash, $pkg;
}

sub to_string {
    my $self = shift;

    return $self->{val};
}

sub equal {
    my $self = shift;
    my $target = shift;
    
    return 1 if ( $self->{val} eq $target->{val} );

    return 0;
}

1;
